package com.example.chat04.redis;

import com.example.chat04.model.ChatMessage;
import com.example.chat04.service.ChatService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component
public class RedisListenerHandler extends MessageListenerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(RedisListenerHandler.class);


    @Value("${redis.channel.msgToAll}")
    private String msgToAll;
    @Autowired
    ChatService chatService;
    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        byte[] body = message.getBody();
        ChatMessage chatMessage ;
        String topic ;
        try {
            chatMessage = (ChatMessage) redisTemplate.getValueSerializer().deserialize(body);
            topic = redisTemplate.getStringSerializer().deserialize(pattern);
            logger.info("Received raw message from topic: {}, raw message content: {}", topic, chatMessage);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return;
        }

        if (msgToAll.equals(topic)){
            logger.info("Send message to all users: {}",chatMessage);
            // 发送消息给所有在线Cid
            chatService.sendMsgToAll(Objects.requireNonNull(chatMessage));
        }else {
            logger.info("No further operation with this topic");
        }
    }
}
